<template>
  <el-row>
    <!--    <el-col :span="leftSpan" :xs="24">-->
    <!--      <div class="flex container">-->
    <!--        <div class="selectTree card">-->
    <!--          <div class="custom-tree-container">-->
    <!--            <div v-for="item in navigationals" :key="item">-->
    <!--              <div class="tree-title flex">-->
    <!--                <b></b><span>{{ item.fieldDesc }}</span>-->
    <!--                <el-icon @click="openTree(item.name)">-->
    <!--                  <Remove />-->
    <!--                </el-icon>-->
    <!--              </div>-->
    <!--              <el-tree-->
    <!--                v-if="showTree[item.name]"-->
    <!--                :data="item.tree"-->
    <!--                :expand-on-click-node="false"-->
    <!--                :filter-node-method="filterNode"-->
    <!--                @node-click="(object) => selectNode(object, item)"-->
    <!--                :props="defaultProps"-->
    <!--                :highlight-current="true"-->
    <!--              />-->
    <!--            </div>-->
    <!--          </div>-->
    <!--        </div>-->
    <!--      </div>-->
    <!--    </el-col>-->
    <el-col :span="24">
      <ContentWrap>
        <!-- 搜索栏 -->
        <el-form
          ref="queryFormRef"
          :inline="true"
          :model="queryParams"
          class="-mb-15px"
          label-width="90px"
        >
          <el-form-item label="关键词" prop="keyword">
            <el-input
              v-model="queryParams.keyword"
              class="!w-240px"
              clearable
              placeholder="请输入关键词"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              end-placeholder="结束日期"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            v-for="item in navigationals"
            :key="item"
            :label="item.fieldDesc"
            :prop="item.name"
          >
            <el-cascader
              :options="item.tree"
              :props="defaultProps"
              @change="(checked) => handleBaseValue(checked, item.name)"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
            <el-button plain type="success" @click="batchRevert" icon="RefreshLeft">
              还原
            </el-button>
            <el-button plain type="primary" @click="setClearDays(title, id)" icon="Edit">
              设置定期清理天数
            </el-button>
            <el-button @click="retreat" type="primary" style="float: right">返回</el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list.list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column
            v-for="(column, index) in list.columns"
            :key="index"
            :prop="column.prop"
            :label="column.label"
            align="center"
          >
            <template #default="scope">
              <el-image
                v-if="imaged(scope.row[column.prop])"
                :src="buildImage(column.prop, scope.row)"
                style="max-width: 50px; max-width: 50px"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><icon-picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <!--          <el-table-column align="center" label="关键字" />-->
          <el-table-column align="center" label="操作">
            <template #default="scope">
              <el-button
                link
                type="primary"
                v-if="meta.detailRoute"
                @click="updateResource(scope.row.id)"
              >
                查看
              </el-button>
              <el-button link type="success" v-if="meta.detailRoute" @click="revert(scope.row.id)">
                还原
              </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <Pagination
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNo"
          :total="total"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <el-dialog
    v-model="showSelectHouseDialogFlag"
    title="选择资源外壳"
    center
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="40%"
    @close="closeSelectHouseDialog"
    align-center
  >
    <el-select v-model="house" placeholder="请选择资源外壳" style="width: 100%">
      <el-option v-for="item in houses" :key="item" :label="item.name" :value="item.id" />
    </el-select>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addResource">下一步</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="showFormDialogFlag"
    :title="formTitle"
    left
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="85%"
    @close="closeForm"
    destroy-on-close
    align-center
  >
    <v-form-render
      ref="vFormRef"
      :form-json="formJson"
      :form-data="formData"
      :option-data="optionData"
    />
    <template #footer>
      <div class="dialog-footer">
        <span v-if="prompt" style="display: block; color: red; margin-bottom: 10px">{{
          prompt
        }}</span>
      </div>
    </template>
  </el-dialog>

  <!-- 设置定期清理天数对话框 -->
  <ClearDaysForm ref="clearDaysFormRef" @success="getList" />
  <Application
    :metaId="id"
    type="10"
    :columns="list.columns"
    :list="selectedItems"
    ref="downAppRef"
  />
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import * as classifyApi from '@/api/classify'
import { Search } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import * as metaApi from '@/api/meta'
import * as houseApi from '@/api/house/book'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import router from '@/router'
import { Remove } from '@element-plus/icons-vue'
import Application from '@/views/download/application.vue'
import download from '@/utils/download'
import ClearDaysForm from './ClearDaysForm.vue'

const route = useRoute()
const id = route.query.id
const title = route.meta.title
const downAppRef = ref<any>()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keyword: null,
  createTime: [],
  deleted: 1
})

const showFormDialogFlag = ref(false)

const formTitle = ref('添加')

const loading = ref(false)

const list = ref([])

const total = ref(0)

const formJson = ref({
  widgetList: [],
  formConfig: {}
})

const formData = ref({})

const optionData = ref({})

interface Tree {
  [key: string]: any
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const house = ref(null)
const houses = ref([])
const handleQuery = () => {
  getList()
}

const defaultProps = {
  label: 'name',
  value: 'id'
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const detail = (dataId) => {
  router.push(meta.value.detailRoute + '?metaId=' + id + '&id=' + dataId)
}
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}

const data = ref<Tree>([])

const queryClassify = async () => {
  if (navigationals.value.length > 0) {
    for (const item of navigationals.value) {
      data.value = await classifyApi.classifyTree(item.classifyCode)
      item.tree = data.value
    }
  }
}
// 返回按钮
const retreat = () => {
  router.go(-1)
}
const getList = async () => {
  list.value = await metaApi.selectData(id, queryParams)
  total.value = list.value.total
}
const selectNode = (object, item) => {
  console.log(item)
  queryParams[item.name] = object.id
  getList()
}
const meta = ref({})
const fieldList = ref([])
const navigationals = ref([])
const leftSpan = ref(0)
const rightSpan = ref(24)
const selectForm = async () => {
  let res = await metaApi.selectForm(id)
  meta.value = res
  let f = JSON.parse(res.tableForm)
  formJson.value.widgetList = f.widgetList
  formJson.value.formConfig = f.formConfig
  res.fieldList.forEach((item) => {
    if (item.navigational) {
      rightSpan.value = 18
      leftSpan.value = 6
      navigationals.value.push(item)
    }
    fieldList.value.push({
      key: item.id,
      label: item.fieldDesc
    })
  })
  queryClassify()
}

const showSelectHouseDialogFlag = ref(false)
const add = async () => {
  formTitle.value = '添加'
  console.log(meta.value)
  if (meta.value.shelled) {
    showSelectHouseDialogFlag.value = true
    houses.value = await houseApi.selectByType(id, '')
  } else {
    addResource()
  }
}
const prompt = ref<string>()
const addResource = async () => {
  if (!house.value && meta.value.shelled) {
    ElMessage('请选择资源外壳!')
    return
  }
  if (house.value && meta.value.shelled) {
    let result = await houseApi.selectInfo(house.value, id)
    if (result && result.length > 0) {
      prompt.value = '注：'
      result.forEach((res) => {
        prompt.value = prompt.value + res.fieldDesc + ','
      })
      prompt.value = prompt.value?.substring(0, prompt.value?.length - 1)
      prompt.value = prompt.value + '需在入库审核前填充。'
    }
    console.log(result)
  }

  updated = false
  showSelectHouseDialogFlag.value = false
  showFormDialogFlag.value = true
}
const closeSelectHouseDialog = () => {
  showSelectHouseDialogFlag.value = false
  house.value = null
}
function isValidJson(str) {
  if (str.startsWith('{') || str.startsWith('[')) {
    if (str.endsWith(']') || str.endsWith('}')) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}
function isNumber(str: string): boolean {
  return /^\d+$/.test(str) // 只包含数字的正则表达式
}
const imaged = (row) => {
  if (!row) {
    return false
  }
  if (isNumber(row)) {
    return false
  }
  return isValidJson(row)
}
const buildImage = (name, row) => {
  // if (row[name]) {
  if (JSON.parse(row[name]).length > 0) {
    return JSON.parse(row[name].replaceAll('\\', ''))[0].url
  } else {
    return ''
  }
}
const vFormRef = ref<any>()
let updated = false
const saveResource = async () => {
  let formDataJson = await vFormRef.value.getFormData()
  formDataJson.house = house.value
  //formDataJson.cover = JSON.stringify(formDataJson.cover)
  if (updated && updateId.value > 0) {
    await metaApi.updateMetaData(id, updateId.value, formDataJson)
  } else {
    await metaApi.createData(id, formDataJson)
  }
  showFormDialogFlag.value = false
  getList()
}
const updateId = ref(0)
const updateResource = async (rid) => {
  updated = true
  formTitle.value = '查看'
  updateId.value = rid
  showFormDialogFlag.value = true
  let res = await metaApi.selectMetaDataOne(id, rid)
  //vFormRef.value.setFieldValue('id', rid)
  await vFormRef.value.setFormData(res)
  vFormRef.value.disableForm()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    let ids = []
    ids.push(id)
    // 发起删除
    await metaApi.deleteMetaDataByIds(route.query.id, ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

//进入资源列表
const impResource = (metaId, id) => {
  router.push('/resource/meta/file?metaId=' + metaId + '&id=' + id)
}
const closeForm = () => {
  //清空表单
  vFormRef.value.resetForm()
  showFormDialogFlag.value = false
}
const showTree = reactive({})
const openTree = (name) => {
  if (showTree[name]) {
    showTree[name] = true
  }
  showTree[name] = !showTree[name]
  console.log(showTree)
}
const selectedItems = ref([])
const handleSelectionChange = (row) => {
  selectedItems.value = row
}

const downloadApp = () => {
  if (selectedItems.value.length == 0) {
    ElMessage.warning('请选择要下载的数据!')
    return
  }
  downAppRef.value.openDialog()
}
const queryFormRef = ref<any>()
const resetQuery = () => {
  queryFormRef.value.resetFields()
  console.log(queryParams)
  handleQuery()
}
const handleBaseValue = (val, name) => {
  let v = JSON.stringify(val).replace('[', '').replace(']', ',')
  queryParams[name] = v
}

// 设置定期清理天数
const clearDaysFormRef = ref()
const setClearDays = async (title: string, id?: number) => {
  clearDaysFormRef.value.open(title, id)
}
const batchRevert = async () => {
  if (selectedItems.value.length == 0 || selectedItems.value.length > 10) {
    ElMessage.warning('请选择要还原的数据!')
    return
  }
  let ids = []
  selectedItems.value.forEach((res) => {
    ids.push(res.id)
  })
  await metaApi.revert(route.query.id, ids)
  await getList()
}
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const revert = async (id) => {
  await message.confirm('确定还原资源吗？')
  let ids = []
  ids.push(id)
  await metaApi.revert(route.query.id, ids)
  await getList()
}

//资源回收站
const recycle = (metaId) => {
  router.push({
    path: '/resource/recycle/index?id=' + metaId
  })
}
onMounted(() => {
  getList()
  selectForm()
})
</script>
<style scoped lang="scss">
.element-plus-tree {
  min-width: 100%;
  display: inline-block !important;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}

.image-slot .el-icon {
  font-size: 30px;
}

.flex {
  display: flex;
}

.container {
  height: 100%;
  justify-content: space-between;

  .selectTree {
    width: 256px;
    margin-right: 20px;
    background-color: #e9effd;

    .tree-title {
      height: 35px;
      align-items: center;
      justify-content: space-between;
      background-color: #ffffff;
      margin: 10px 0;
      padding: 0 10px;
      box-sizing: border-box;
      border-radius: 5px;

      b {
        display: block;
        border-radius: 2px;
        width: 3px;
        height: 45%;
        background-color: #3a8fec;
      }

      span {
        flex: 1;
        margin-left: 15px;
        font-size: 15px;
      }
    }
  }

  .content {
    flex: 1;
    overflow: auto;
  }
}

:deep(.el-tree) {
  background-color: transparent;
}

.dialog-footer {
  text-align: center;
}
</style>
